# coding: utf-8
import os, json, requests
from django.conf import settings
from .pub_tool import is_can_do


def get_stock_workday_list(stock_data):
    klines = stock_data["data"]["klines"]
    stock_workday_list = []
    for kline in klines:
        stock_workday_list.append(kline.split(',')[0])
    return stock_workday_list


def json_to_file(filepath, stock_code):
    stock_url = "http://push2his.eastmoney.com/api/qt/stock/kline/get?fields1=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13&fields2=f51,f52,f53,f54,f55,f56,f57,f58,f59,f61&beg=0&end=20500101&ut=fa5fd1943c7b386f172d6893dbfba10b&rtntype=6&secid={}&klt=101&fqt=1".format(
        stock_code)
    html = requests.get(stock_url)

    stock_data = json.loads(html.text, encoding='utf-8')

    with open(filepath, 'w', encoding='utf-8') as f:
        f.write(json.dumps(stock_data, indent=2, ensure_ascii=False))


def get_stock_data(stock_code):
    filepath = os.path.join(settings.TEMP_DIR, stock_code + '.json')

    if is_can_do('a_get_stock_data_'+stock_code, "09:25", "15:05", count=3, interval_minute=60):
        # 每天9:25至15:05 之间可以获取3次数据，每次间隔60分钟
        json_to_file(filepath=filepath, stock_code=stock_code)

    elif is_can_do('b_get_stock_data_'+stock_code, begin_time="15:05", count=2, interval_minute=120):
        # 每天15:10之后可以获取2次数据，每次间隔120分钟
        json_to_file(filepath=filepath, stock_code=stock_code)

    if not os.path.exists(filepath):
        json_to_file(filepath=filepath, stock_code=stock_code)
    with open(filepath, 'r', encoding='utf-8') as stock_f:
        stock_data = json.loads(stock_f.read())

    return stock_data
